package cn.xiaoyacode.ddd.infrastructure.persistence.mysql;

import cn.xiaoyacode.ddd.domain.user.model.UserEntity;
import cn.xiaoyacode.ddd.domain.user.model.vo.UserId;
import cn.xiaoyacode.ddd.domain.user.repository.IUserRepository;
import cn.xiaoyacode.ddd.infrastructure.converter.user.UserConvert;
import cn.xiaoyacode.ddd.infrastructure.persistence.mysql.mapper.user.UserMapper;
import cn.xiaoyacode.ddd.infrastructure.persistence.mysql.po.user.UserPO;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author xieya
 * @date 2021/7/15
 */
@Repository
public class UserRepositoryImpl extends ServiceImpl<UserMapper, UserPO> implements IUserRepository, IService<UserPO> {
    @Autowired
    private UserMapper userMapper;

    /**
     * 创建用户
     * SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@49e479da]
     * was not registered for synchronization because synchronization is not active
     *
     * @param user 用户创建参数
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserId createUser(UserEntity user) {
        Date now = new Date(System.currentTimeMillis());
        UserPO userPo = UserConvert.INSTANCE.covert(user)
                .setCreateTime(now)
                .setUpdateTime(now);
        userMapper.insert(userPo);
        return new UserId(userPo.getId());
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean isExistUser(String username) {
        return userMapper.selectCount(username) != 0;
    }
}
